import { styled, Access } from '@umijs/max'
import { useRequest } from 'ahooks'
import { Card, Space, Button, Modal, Input, message, Spin } from 'antd'
import { getInvoiceStatus, invoiceLogin, postCode, getQrCode } from './services'
import { CheckCircleFilled, CloseCircleFilled, InfoCircleFilled } from '@ant-design/icons'
import { useState } from 'react'

const Row = styled.div`
  display: flex;
  gap: 16px;

  .status-box {
    height: 26px;
    padding: 0 8px;
    display: flex;
    align-items: center;
    background: #f5fff5;
    border: 1px solid green;
    color: green;
    gap: 8px;
  }

  .status-box-err {
    background: #fcf4f4;
    border: 1px solid red;
    color: red;
  }
`

let interval
const InvoiceStatusHook: React.FC = () => {
  const status = useRequest(getInvoiceStatus)
  const loginReq = useRequest(invoiceLogin, {manual: true})
  const codeReq = useRequest(postCode, {manual: true})
  const qrCodeReq = useRequest(getQrCode, {manual: true})
  const [codeOpen, setCodeOpen] = useState(false)
  const [qrCodeOpen, setQrCodeOpen] = useState(false)
  const [code, setCode] = useState('')
  const [canReGet, setCanReGet] = useState(false)
  const [countDown, setCountDown] = useState(60)

  const codeCancel = () => {
    setCodeOpen(false)
  }
  const openQrCodeModal = () => {
    qrCodeReq.runAsync()
    .then(_res => {
      if (_res.code === '200') {
        setQrCodeOpen(true)
        codeCancel()
      } else {
        message.error(_res.text)
      }
    })
  }
  const login = () => {
    loginReq.runAsync()
    .then(res => {
      if (res.code === '200') {
        openQrCodeModal()
      } else if (res.code === '1921') {
        setCanReGet(false)
        setCountDown(60)
        interval = setInterval(() => {
          setCountDown(count => {
            if (count <= 0) {
              setCanReGet(true)
              clearInterval(interval!)
              interval = null
            }
            return count - 1
          })
        }, 1000)
        setCodeOpen(true)
      } else {
        message.error(res.text)
      }
    })
  }
  const codeOk = () => {
    const _code = code.trim()
    if (!_code) {
      message.error('请输入验证码')
    } else {
      codeReq.runAsync({code: _code})
      .then(res => {
        if (res.code === '200') {
          openQrCodeModal()
        } else {
          message.error(res.text)
        }
      })
    }
  }
  const reGet = () => {
    login()
    codeCancel()
  }
  const onQrCodeCancel = () => {
    setQrCodeOpen(false)
  }
  const onQrCodeOk = () => {
    status.run()
    onQrCodeCancel()
  }

  return (
    <Card>
      <Spin spinning={status.loading}>
        <Row>
          <h3>开票设备状态</h3>
          <Access accessible={!!status.data}>
            <view className={status.data?.code === '200' ? 'status-box' : 'status-box status-box-err'}>
              {status.data?.code === '200' ? <CheckCircleFilled /> : <CloseCircleFilled />}
              {status.data?.code === '200' ? '成功' : '失败'}
            </view>
            {status.data?.code === '200' ? '' : <div style={{lineHeight: `26px`, color: 'red'}}>失败原因：{status.data?.text}</div> }
          </Access>
        </Row>
      </Spin>
      <Access accessible={status.data?.code !== '200'}>
        <Space>
          <Button type='primary' onClick={login} loading={loginReq.loading || qrCodeReq.loading}>登录</Button>
          <Button type='primary' onClick={openQrCodeModal} loading={qrCodeReq.loading}>获取税务APP登录二维码</Button>
        </Space>
      </Access>
      <Modal
        open={codeOpen}
        title='设置验证码'
        onCancel={codeCancel}
        footer={[
          <Button key='cancel' onClick={codeCancel}>取消</Button>,
          <Button key='ok' type='primary' onClick={codeOk} loading={codeReq.loading || qrCodeReq.loading}>下一步</Button>,
        ]}
      >
        <div style={{display: 'flex', marginBottom: 12}}>
          <div style={{flexGrow: 1, lineHeight: '32px'}}>验证码：</div>
          <Input
            placeholder='请输入验证码'
            value={code}
            onChange={({target}) => setCode(target.value)}
          />
        </div>
        <div style={{textAlign: 'right'}}>
          <Access accessible={canReGet} fallback={<div>{countDown}秒后可重新获取验证码</div>}>
            <a onClick={reGet}>重新获取</a>
          </Access>
        </div>
      </Modal>
      <Modal
        open={qrCodeOpen}
        title='税务APP登录二维码'
        onCancel={onQrCodeCancel}
        footer={false}
      >
        <div style={{display: 'flex', justifyContent: 'center', marginTop: 16}}>
          <img src={`data:image/jpeg;base64,${qrCodeReq.data?.data}`} style={{width: 200, height: 200}} />
        </div>
        <div style={{display: 'flex', justifyContent: 'center', marginTop: 16}}>
          <Space>
            <InfoCircleFilled style={{color: '#ffbf00'}} />
            <span>请使用税务APP扫描二维码进行人脸识别</span>
          </Space>
        </div>
        <div style={{display: 'flex', justifyContent: 'center', marginTop: 24}}>
          <Button type='primary' onClick={onQrCodeOk}>我已验证通过</Button>
        </div>
      </Modal>
    </Card>
  )
}

export default InvoiceStatusHook
